﻿using Abp.Authorization;
using Basefr.App;
using Microsoft.AspNetCore.Mvc;
using Paas.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Paas.Core.MetaEnums.Entities;
using Paas.App.Interface.MetaEnums;
using Paas.App.Interface.MetaEnums.Messages;
using Abp.UI;
using System.Linq.Expressions;
using Abp.Linq.Expressions;
using Paas.App.Interface.MetaEnums.Dtos;
using Abp.Logging;
using Paas.Core.Const.Enums;

namespace Paas.App.MetaEnums
{
    [Route("meta-metaEnum")]

    [AbpAuthorize()]
    public class MetaEnumAppService : AppService, IMetaEnumAppService
    {
        private readonly IMainRepository<MetaEnum, Guid> _MetaEnumRepo;


        public MetaEnumAppService(IMainRepository<MetaEnum, Guid> MetaEnumRepo)
        {
            _MetaEnumRepo = MetaEnumRepo;
        }

        [HttpPost(nameof(SaveMetaEnum))]
        public async Task<SaveMetaEnumOutput> SaveMetaEnum(SaveMetaEnumInput input)
        {
            if (input == null) throw new UserFriendlyException("保存字段信息失败：input为空！");
            if (string.IsNullOrWhiteSpace(input.Item.Code)) throw new UserFriendlyException("保存字段信息失败：Code为空！");

            var entity = ObjectMapper.Map<MetaEnum>(input.Item);
            if (input.Item?.Id != null && input.Item?.Id != Guid.Empty)
            {
                await _MetaEnumRepo.UpdateAsync(entity);
                return new SaveMetaEnumOutput();
            }

            Expression<Func<MetaEnum, bool>> predicate = p => p.Code == input.Item.Code;
            var result = await _MetaEnumRepo.GetAllListAsync(predicate);
            if (result.Count>0) throw new UserFriendlyException("保存字段信息失败：Code重复！请检查名称", LogSeverity.Warn);

            //设置一些默认的值
            entity.IsPublic= false;
            entity.CurrentStatus ??= MetaStatus.New;

            await _MetaEnumRepo.InsertAsync(entity);
            return new SaveMetaEnumOutput();
        }

        [HttpPost(nameof(SearchMetaEnum))]
        public async Task<SearchMetaEnumOutput> SearchMetaEnum(SearchMetaEnumInput input)
        {
            Expression<Func<MetaEnum, bool>> predicate = p => true;
            if (!string.IsNullOrWhiteSpace(input.Code))
            {
                predicate = predicate.And(p => p.Code == input.Code);
            }
            if (!string.IsNullOrWhiteSpace(input.Name))
            {
                predicate = predicate.And(p => p.Name.Contains(input.Name.Trim()));
            }
            if (input.IsPublic!=null)
            {
                predicate = predicate.And(p => p.IsPublic == input.IsPublic);
            }
            if (input.ApplicationId!=null)
            {
                predicate = predicate.And(p => p.ApplicationId == input.ApplicationId);
            }

            var result = await _MetaEnumRepo.GetAllListAsync(predicate);
            var res = result.OrderByDescending(p => p.SortNum).OrderBy(p => p.CreationTime).Skip(input.SkipCount).Take(input.MaxResultCount).ToList();
            var totalCount = result.Count();
            var resultItems = ObjectMapper.Map<List<MetaEnumDto>>(res);
            return new SearchMetaEnumOutput { Items = resultItems, TotalCount = totalCount };
        }

        [HttpPost(nameof(DeleteMetaEnum))]
        public async Task<DeleteMetaEnumOutput> DeleteMetaEnum(DeleteMetaEnumInput input)
        {
            //await _MetaEnumRepo.
            await _MetaEnumRepo.DeleteAsync(input.Id);
            return new DeleteMetaEnumOutput();
        }

        /// <summary>
        /// 发布字段
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        //[HttpPost(nameof(PublicMetaEnum))]
        //public async Task PublicMetaEnum(PublicMetaEnumInput input)
        //{
        //    if (input!=null&&input?.Ids.Count>0)
        //    {
        //        foreach (var item in input.Ids)
        //        {
        //            var uData = await _MetaEnumRepo.GetAsync(item);
        //            if (uData == null) throw new UserFriendlyException("未找到需要更新的对象！");
        //            if (uData.CurrentStatus != MetaStatus.Released&& uData.CurrentStatus != MetaStatus.Deleted)
        //            {
        //                uData.CurrentStatus = MetaStatus.Released;
        //                await _MetaEnumRepo.UpdateAsync(uData);
        //            }
        //        }
        //    }
        //}

    }
}
